import $ from '../../utils/jquery-vendor';
import {message, Modal} from 'antd';
import cookie from 'react-cookies';
import store from '../../store';
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import {ExclamationCircleOutlined} from '@ant-design/icons'
import ExportJsonExcel from "js-export-excel";

const {
    REACT_APP_SERVER_URL,
    REACT_APP_FILE_URL,
    REACT_APP_PROJECT_NAME,
} = process.env;

console.log(REACT_APP_SERVER_URL)
Nprogress['configure']({showSpinner: false})
const {confirm} = Modal;
const commonConfig = {
    // url: REACT_APP_SERVER_URL,
    url: "http://47.92.39.27:8090/",
    fileUrl: REACT_APP_FILE_URL,
    react_project_name: REACT_APP_PROJECT_NAME,
        projectName: 'react_template_admin',
    pageNumber: 1,
    pageSize: 10,
    totalRow: 0,
    isLogin: false,

    options: {
        navList: [
            {name: '首页', path: 'homePage'},
            {name: 'XXXXX', path: 'dataCenter'},
            {name: '系统管理', path: 'system'}
        ],
        dataCenterNavList: [
            {name: 'XXXX', path: 'resourceInventory'},
            {name: 'XXXX', path: 'dataManagement'},
            {name: 'XXXX', path: 'projectManagement'},
        ],
        letterList: ['A', 'B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R', 'S','T','U','V','W','X','Y','Z'],
        regex: {
            allView: /(docx|txt|json|xls|xlsx|csv|pdf|mp3|mp4|jpg|png|jpeg|gif|xml|js|jsx|ts)$/,
            doc: /(pdf|docx|xls|xlsx|csv|txt|xml|json|js|jsx|ts)$/,
            image: /(jpg|png|jpeg|gif)$/,
            audio: /(mp3)$/,
            video: /(mp4)$/,
            otherDoc: /(js|jsx|ts)$/,
            excel: /(xlsx|xls|csv)$/,
            word: /(docx)$/,
            ppt: /(pptx)$/,
            commonTxt: /(xml|js|jsx|ts)$/
        }
    },
    /**
     * 设置地址栏URL参数  返回react-router-dom search的参数
     * @param params
     * @returns {string}
     */
    setUrlParams(params) {
        let paramsArr = [];
        for (const paramsKey in params) {
            if (params.hasOwnProperty(paramsKey))
                paramsArr.push(paramsKey + '=' + encodeURIComponent(encodeURIComponent(params[paramsKey])));
        }
        return paramsArr.join('&');
    },
    /**
     * 页面跳转
     * @param _this
     * @param pathname
     * @param params
     */
    redirectPage(_this, pathname, params) {
        _this.props.history.push({
            pathname: pathname ? '/view/' + pathname : '/view',
            search: this.setUrlParams(params || {})
        });
    },
    /**
     * 页面跳转默认
     * @param _this
     * @param pathname
     * @param params
     */
    redirectPageDefault(_this, pathname, params) {
        _this.props.history.push({
            pathname: pathname ? '/' + pathname : '/view',
            search: this.setUrlParams(params || {})
        });
    },
    /**
     * 页面跳转-打开新窗口
     * @param pathname
     * @param params
     */
    redirectPageOpen(pathname, params) {
        let origin = window.location.origin + process.env.REACT_APP_PROJECT_NAME + '/#';
        window.open(origin + (pathname ? ('/' + pathname + '?') : '/view') + this.setUrlParams(params));
    },
    /**
     * 获取url参数并返回对象
     * @param _this
     */
    getUrlParams(_this) {
        const {search} = _this.props.location;
        let params = decodeURIComponent(decodeURIComponent(search));
        if (!params) return {};
        params = params.substring(params.lastIndexOf('?') + 1);
        params = params.split('&');
        let resultObj = {};
        for (const paramsKey in params) {
            let param = params[paramsKey].split('=');
            resultObj[param[0]] = param[1];
        }
        return resultObj;
    },
    /**
     * ajax文件请求
     * @param url
     * @param data
     * @param successCallback
     * @param errCallback
     * @param beforeCallback
     * @param completeCallback
     * @returns {*}
     */
    ajaxFileMethods(url, data, successCallback, errCallback, beforeCallback, completeCallback) {
        let load;
        $.ajax({
            type: 'POST',
            url: this.url + url,
            data,
            headers: {
                'JWT-token': this.getCookies('token')
            },
            processData: false,
            contentType: false,
            beforeSend: () => {
                this.startProgress();
                if (beforeCallback) {
                    beforeCallback();
                }
                load = message.loading({content: '数据正在上传中，请耐心等待...', key: 'uploadLoading', duration: 0});
            },
            success(res) {
                if (successCallback) successCallback(res);
            },
            error(err) {
                message.error({content: '服务器忙，请稍后再试', key: 'fail'});
                if (errCallback) errCallback(err);
            },
            complete: () => {
                if (completeCallback) {
                    completeCallback();
                }
                setTimeout(load, 0);
                this.endProgress();
            }
        });
    },
    /**
     * ajax没有文件请求
     * @param url
     * @param data
     * @param successCallback
     * @param errCallback
     * @param beforeCallback
     * @param completeCallback
     * @param type
     * @param async
     * @returns {*}
     */
    ajaxNoFileMethods(url, data, successCallback, errCallback, beforeCallback, completeCallback, type, async) {
        let result;
        $.ajax({
            type: type ? 'POST' : 'GET',
            url: this.url + url,
            data,
            async: !async,
            headers: {
                'JWT-token': this.getCookies('token')
            },
            beforeSend: () => {
                this.startProgress();
                if (beforeCallback) {
                    beforeCallback();
                } else {

                    // load = message.loading({content: '数据加载中', key: 'load', duration: 0});
                }
            },
            success: (res) => {
                // this.messageCustomService(res,callback=>{})
                // if (res.code==='403'){
                //
                // }else {
                if (async) {
                    result = res;
                } else {
                    if (successCallback) successCallback(res);
                }
                // }
            },
            error(err) {
                console.log(err);
                message.error({content: '服务器忙，请稍后再试', key: 'fail'});
                if (errCallback) errCallback(err);
            },
            complete: () => {
                this.endProgress();
                if (completeCallback) {
                    completeCallback();
                } else {
                    // setTimeout(load, 0);
                }
            }
        });
        if (async) {
            return result;
        }
    },
    /**
     * ajax不指定URL请求
     * @param url
     * @param data
     * @param successCallback
     * @param errCallback
     * @param beforeCallback
     * @param completeCallback
     * @param type
     * @param async
     * @param dataType
     * @returns {*}
     */
    ajaxMethods(url, data, successCallback, errCallback, beforeCallback, completeCallback, type, async, dataType) {
        let result;
        $.ajax({
            type: type ? 'POST' : 'GET',
            url: url,
            data,
            async: !async,
            headers: {
                'JWT-token': this.getCookies('token')
            },
            dataType: dataType ? dataType : 'json',
            beforeSend: () => {
                this.startProgress();
                if (beforeCallback) {
                    beforeCallback();
                } else {
                    // load = message.loading({
                    //     content: '数据加载中',
                    //     key: 'load',
                    //     duration: 0
                    // });
                }
            },
            success(res) {
                if (async) {
                    result = res;
                } else {
                    if (successCallback) successCallback(res);
                }
            },
            error(err) {
                console.log(err);
                message.error({content: '服务器忙，请稍后再试', key: 'fail'});
                if (errCallback) errCallback(err);
            },
            complete: () => {
                this.endProgress();
                if (completeCallback) {
                    completeCallback();
                } else {
                    // setTimeout(load, 0);
                }
            }
        });
        if (async) {
            return result;
        }
    },
    startProgress() {
        Nprogress['start']();
    },
    endProgress() {
        Nprogress['done']();
    },
    /**
     * 下载文件
     * @param item
     * @returns {string}
     */
    downloadFile(item) {
        return item ? `${this.url}file/download?bucketName=${item['bucketName']}&fileId=${item.fileUrl}` : '';
    },
    /**
     * 过滤信息
     * @param content
     * @param size
     */
    filterInfo(content, size) {
        let html = '';
        if (content) {
            let infoArr = content.split(/[\n\r]/g);
            let filterArr = [];
            for (const infoArrKey in infoArr) {
                if (infoArr.hasOwnProperty(infoArrKey)) {
                    if (infoArr[infoArrKey]) {
                        filterArr.push(infoArr[infoArrKey]);
                    }
                }
            }
            for (let i = 0; i < filterArr.length; i++) {
                let text = filterArr[i].replace(/\s+/g, '');
                if (size && filterArr.length > size) {
                    if (i < size) {
                        if (text) {
                            html += `<p>${text}${(i + 1 === size ? '...' : '')}</p>`;
                        }
                    }
                } else {
                    if (text) {
                        html += `<p>${text}</p>`;
                    }
                }
            }
        }
        return html;
    },
    /**
     * 字符串截取
     * @param info
     * @param num
     * @returns {string|*}
     */
    fontSplit(info, num) {
        if (info.length > num) {
            return info.substr(0, num) + '...';
        } else {
            return info;
        }
    },
    /**
     * 设置cookie 以秒为单位，默认是1天
     * @param obj
     * @param maxAge
     */
    setCookies(obj, maxAge) {
        let day = 60 * 60 * 24; // 以秒为单位 1天
        for (const objKey in obj) {
            if (obj.hasOwnProperty(objKey))
                cookie.save(objKey, obj[objKey], {path: '/', maxAge: maxAge ? maxAge : day});
        }
    },
    /**
     * 获取cookie
     * @param key
     * @param getAll
     */
    getCookies(key, getAll) {
        if (getAll) {
            return cookie.loadAll();
        } else {
            return cookie.load(key);
        }
    },
    /**
     * 删除cookie
     * @param key
     * @param removeAll
     */
    removeCookies(key, removeAll) {
        if (removeAll) {
            let msg = cookie.loadAll();
            for (const msgKey in msg) {
                if (msg.hasOwnProperty(msgKey))
                    cookie.remove(msgKey, {path: '/', maxAge: 0});
            }
        } else {
            cookie.remove(key, {path: '/', maxAge: 0});
        }
    },
    /**
     * 判断用户登录状态
     * @returns {boolean}
     */
    judgeUserLoginStatus() {
        // return !!this.getCookies('token');
        return true
    },
    /**
     * 退出登录
     */
    logOutService() {
        // this.ajaxNoFileMethods('user/loginOut', {
        //     accunt: this.getUserInfo().accunt,
        //     refreshToken: this.getCookies('refreshToken')
        // }, msg => {
        //     this.removeCookies(null, true);
        //     store.dispatch({type: 'isLogin', payload: false});
        // }, null, null, null, true);
        commonConfig.setCookies({ isLogin: false });
        this.removeCookies(null, true);
        store.dispatch({type: 'isLogin', payload: false});
    },
    /**
     * 刷新token
     * @param callback
     */
    refreshToken(callback) {
        this.ajaxNoFileMethods('user/token/refresh', {refreshToken: this.getCookies('refreshToken')}, msg => {
            if (msg.code === '10000') {
                this.setCookies({token: msg.data});
                if (callback) callback();
            } else if (msg.code === '10001') {
                message.info('Token已过期，请重新登陆');
                this.logOutService();
            }
        }, null, null, null, true);
    },
    /**
     * 验证token获取数据
     * @param url
     * @param data
     * @param successCallback
     * @param errCallback
     * @param beforeCallback
     * @param completeCallback
     * @param type
     * @param async
     */
    validateTokenLoadData(url, data, successCallback, errCallback, beforeCallback, completeCallback, type, async) {
        if (this.getCookies('token')) {
            this.ajaxNoFileMethods(url, data, msg => {
                this.validateCallbackOptions(msg, successCallback, () => this.validateTokenLoadData(url, data, successCallback, errCallback, beforeCallback, completeCallback, type, async));
            }, errCallback, beforeCallback, completeCallback, type, async);
        } else {
            this.logOutService()
            successCallback();
        }
    },
    /**
     * 验证token回调配置
     * @param msg
     * @param callback
     * @param load
     */
    validateCallbackOptions(msg, callback, load) {
        if (msg.result === 'false' && msg.code) {
            if (msg.code === '10002') {
                this.refreshToken(load);
            } else if (msg.code === '10001') {
                this.logOutService();
            } else if (/(401|403)$/.test(msg.code)) {
                this.messageCustomService(msg, null, true);
            } else {
                if (callback) callback(msg);
            }
        } else {
            if (callback) callback(msg);
        }
    },
    /**
     * 切割数组，把一个数据分割成多个组
     * @param array
     * @param subGroupLength
     * @returns {[]}
     */
    arraySlice(array, subGroupLength) {
        let index = 0;
        let newArray = [];
        while (index < array.length) {
            newArray.push(array.slice(index, index += subGroupLength));
        }
        return newArray;
    },
    /**
     * 生成UUID
     * @returns {string}
     */
    randomUUID() {
        let s = [];
        let hexDigits = '0123456789abcdef';
        for (let i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = '4';
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
        s[8] = s[13] = s[18] = s[23] = '-';
        return s.join('');
    },
    setKeys(dataSource) {
        for (let i = 0; i < dataSource.length; i++) {
            dataSource[i].key = i + 1;
        }
    },
    /**
     * 根据Value获取key
     * @param obj
     * @param value
     * @returns {string}
     */
    getValueByKey(obj, value) {
        for (const objKey in obj) {
            if (obj.hasOwnProperty(objKey)) {
                if (obj[objKey] === value) {
                    return objKey;
                }
            }
        }
    },
    /**
     * 根据Key获取Value
     * @param obj
     * @param key
     * @returns {string}
     */
    getKeyByValue(obj, key) {
        for (const objKey in obj) {
            if (obj.hasOwnProperty(objKey)) {
                if (parseInt(objKey) === key) {
                    return obj[objKey];
                }
            }
        }
    },
    /*获取json数据的name*/
    getJsonValueByName(msg, value) {
        for (let i = 0; i < msg.length; i++) {
            if (msg[i].value === value) {
                return msg[i].name;
            }
        }
    },
    /*获取用户信息*/
    getUserInfo() {
        return this.getCookies('userInfo') || {};
    },

    /**
     * 删除弹窗
     * @param text
     * @param okCallback
     * @param noCallback
     */
    deleteModelWindow(okCallback, noCallback, text) {
        confirm({
            icon: <ExclamationCircleOutlined style={{color: 'red'}}/>,
            content: '确定删除' + (text || '') + '吗？',
            centered: true,
            okText: '确定',
            cancelText: '取消',
            onOk: okCallback,
            onCancel: noCallback
        });
    },
    /*删除文件夹*/
    deleteFileService({id}, callback) {
        this.validateTokenLoadData('files/info/delete/' + id, null, msg => {
            this.messageService(msg, callback, '删除');
        })
    },
    /*正确错误提示*/
    messageService(msg, callback, text) {
        let result = msg.code.toString() === '200';
        if (result) {
            message.success({content: text + '成功', key: 'logout'});
        } else {
            message.error({content: text + '失败', key: 'logout'});
        }
        if (callback) callback(result);
    },
    /*自定义正确错误提示*/
    messageCustomService(msg, callback, noMsg) {
        let result = msg.code.toString() === '200';
        if (result) {
            if (!noMsg) message.success({content: msg.message || msg.msg, key: 'custom_msg'});
        } else {
            message.error({content: msg.message || msg.msg, key: 'custom_msg'});
        }
        if (callback) callback(result);
    },
    /*获取当前导航模块*/
    getCurrentNavActive(navList, default_nav) {
        let hash = window.location.hash;
        let subHash = hash.substring(0, hash.lastIndexOf('?'));
        if (subHash) {
            hash = subHash
        }
        let hashArr = hash.split('/');

        let active = default_nav;
        for (let i = 0; i < navList.length; i++) {
            let path = navList[i].path;
            for (let j = 0; j < hashArr.length; j++) {
                if (hashArr[j] === path) {
                    active = path;
                }
            }
        }
        return active;
    },
    /*获取用户列表*/
    getUserList(callback) {
        this.validateTokenLoadData('user/list', null, msg => callback(msg.data))
    },
    /*获取单位列表*/
    getUnitList(callback) {
        this.ajaxNoFileMethods('workunit/list', null, msg => callback(msg.data));
    },
    /*获取角色列表*/
    getRoleList(callback) {
        this.validateTokenLoadData('role/list', null, msg => callback(msg.data));
    },
    /**
     * 验证用户名
     * @param values
     * @param callback
     */
    validateAccountName(values, callback) {
        this.ajaxNoFileMethods('user/verify/accunt', {
            accunt: values.accunt
        }, data => {
            if (data.code === '200') {
                if (callback) callback();
            } else {
                message.error({content: data.message, key: 'account'});
            }
        }, null, null, null, true);
    },
    /**
     * 验证手机号重复
     * @param params
     * @param callback
     */
    validateMobile(params, callback) {
        this.validateTokenLoadData('user/verify/mobile', params, msg => {
            if (msg.code === '200') {
                if (callback) callback();
            } else {
                message.error({content: msg.message, key: 'mobile'});
            }
        }, null, null, null, true);
    },
    /*添加文件到formData*/
    appendFileToFormData(obj, formData) {
        for (let i = 0; i < obj.files.length; i++) {
            if (!obj.files[i].id) {
                formData.append('files', obj.files[i]);
            }
        }
    },
    /*过滤图片和文件*/
    filterImageAndFile(msg) {
        let imgList = [], files = [];
        for (let i = 0; i < msg.length; i++) {
            msg[i]['key'] = i + 1;
            if (this.options.regex.image.test(msg[i].type.toLocaleLowerCase())) {
                imgList.push(msg[i]);
            } else {
                files.push(msg[i]);
            }
        }
        return {imgList, files};
    },
    /*获取当前导航模块*/
    getHeadCurrentModule() {
        return this.getCurrentNavActive(this.options.navList)
    },
    /**
     * 导出echarts图表为图片
     * @param charts
     * @param pixelRatio 导出的图片分辨率比率 默认3
     */
    exportChartsImage(charts, pixelRatio) {
        let url = charts.getConnectedDataURL({
            pixelRatio: pixelRatio || 3,　　//导出的图片分辨率比率,默认是1
            backgroundColor: '#fff',　　//图表背景色
            type: 'png',
            excludeComponents: [　　//保存图表时忽略的工具组件,默认忽略工具栏
                'toolbox'
            ]
        });
        let a = document.createElement('a');
        a.download = new Date().getTime().toString();
        a.href = url;
        a.target = '_blank';
        document.body.append(a);
        a.click();
        a.remove();
    },
    /**
     * 计算数组总和
     * @param msg
     * @returns {number}
     */
    countArrayTotal(msg) {
        let count = 0;
        for (let i = 0; i < msg.length; i++) {
            count += parseFloat(msg[i]);
        }
        return count;
    },
    /**
     * 金额转换
     * @param num
     * @returns {{unit: string, num: number}}
     */
    unitConvert(num) {
        let moneyUnits = ['元', '万元', '亿元', '万亿']
        let dividend = 10000;
        let curentNum = num || 0;
        //转换数字 
        let curentUnit = moneyUnits[0];
        //转换单位 
        for (let i = 0; i < 4; i++) {
            curentUnit = moneyUnits[i]
            if (this.strNumSize(curentNum) < 5) {
                break;
            }
            curentNum = curentNum / dividend
        }
        let m = {num: 0, unit: ''}
        m.num = curentNum.toFixed(2)
        m.unit = curentUnit;
        return m;
    },
    strNumSize(tempNum) {
        let stringNum = tempNum ? tempNum.toString() : "0"
        let index = stringNum.indexOf('.')
        let newNum = stringNum;
        if (index !== -1) {
            newNum = stringNum.substring(0, index)
        }
        return newNum.length
    },

    /*读取消息*/
    readMessage(ids, callback) {
        this.validateTokenLoadData('info/update', {ids}, msg => {
            if (callback) callback(msg);
        }, null, null, null, true)
    },
    /**
     * 导出表格数据为excel
     * @param columns
     * @param dataSource
     * @param fileName
     */
    exportExcel(columns, dataSource, fileName) {
        let sheetFilter = [], sheetHeader = [];
        for (let i = 0; i < columns.length; i++) {
            sheetHeader.push(columns[i].title);
            sheetFilter.push(columns[i].dataIndex);
        }
        let options = {
            fileName: fileName || new Date().getTime(),
            datas: [
                {
                    sheetData: dataSource,
                    sheetName: 'sheet',
                    sheetFilter,
                    sheetHeader
                }
            ]
        }
        let toExcel = ExportJsonExcel({...options});
        toExcel.saveExcel();
    },
    /**
     * 下载服务接口
     * @param url
     * @param params
     */
    downloadService(url, params) {
        let data = [];
        for (const paramsKey in params) {
            if (params.hasOwnProperty(paramsKey)) {
                data.push(paramsKey + '=' + params[paramsKey]);
            }
        }
        let elem = document.createElement("a");
        elem.href = this.url + url + '?' + data.join("&");
        elem.download = new Date().getTime().toString();
        document.body.append(elem);
        elem.click();
        elem.remove();
    },
    /**
     * 过滤文件返回集合
     * @param msg
     * @returns {{文档: [], 图片: [], 其它: [], 视频: [], 音频: []}}
     */
    filterFilterReturnList(msg) {
        msg = msg || [];
        let imagesArr = [], videoArr = [], audioArr = [], docArr = [], otherArr = [];
        const {image, video, audio, doc} = this.options.regex;
        for (let i = 0; i < msg.length; i++) {
            let item = msg[i];
            const {type} = item;
            let fileType = type.toLowerCase();
            if (image.test(fileType)) { // 图片过滤
                imagesArr.push(item);
            } else if (video.test(fileType)) { // 视频过滤
                videoArr.push(item);
            } else if (audio.test(fileType)) { // 音频过滤
                audioArr.push(item);
            } else if (doc.test(fileType)) { // 文档过滤
                docArr.push(item);
            } else { // 其它过滤
                otherArr.push(item);
            }
        }
        return {
            '\u56fe\u7247': imagesArr,
            '\u89c6\u9891': videoArr,
            '\u97f3\u9891': audioArr,
            '\u6587\u6863': docArr,
            '\u5176\u5b83': otherArr
        };
    },
    /**
     * 过滤文件预览类型
     * @param bucketName
     * @param fileUrl
     * @param name
     * @param type
     */
    filterRedirectType({bucketName, fileUrl, name, type}) {
        let fileType = type.toLowerCase();
        const {commonTxt, excel, word, ppt} = this.options.regex;
        if (excel.test(fileType)) {
            fileType = 'excel';
        } else if (word.test(fileType)) {
            fileType = 'word';
        } else if (ppt.test(fileType)) {
            fileType = 'powerPoint';
        } else if (commonTxt.test(fileType)) {
            fileType = 'xml';
        }
        this.redirectPageOpen(`viewer/${fileType}Viewer`, {bucketName, fileUrl, name});
    },
    /*计算视频时长*/
    countVideoDuration(duration) {
        let minute = parseInt((duration % 3600) / 60);
        if (minute < 10) {
            minute = "0" + minute;
        }
        let second = (Math.floor(duration % 60) / 100).toString();
        second = second.substring(second.lastIndexOf('.') + 1);
        second = parseInt(second);
        if (second < 10) {
            second = "0" + second;
        }
        return minute + ':' + second;
    },
    /**
     * 获取服务端文件内容
     * @param bucketName
     * @param fileUrl
     * @param callback
     */
    getServiceFileContent({bucketName, fileUrl}, callback) {
        this.ajaxMethods(this.downloadFile({bucketName, fileUrl}), null, msg => {
            callback(msg);
        }, null, null, null, false, false, 'text');
    }
};
export default commonConfig;